from rest_framework import serializers

from api.models import Book, User


# 群体操作

class BookListSerializer(serializers.ListSerializer):
    '''
    使用此序列化器完成更新多个对象
    '''

    # 重写update方法完成更新
    def update(self, instance, validated_data):
        print(instance)
        print(validated_data)
        print(self.child)

        for index, obj in enumerate(instance):
            # 每遍历一次 就修改一次
            self.child.update(obj, validated_data[index])


class BookModelSerializerV3(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ("book_name", "price")
        extra_kwargs = {
            "book_name": {
                "required": True,
                "min_length": 2,
                "error_messages": {
                    "required": "图书必须提供",
                    "min_length": "图书名不得少于两个字符",
                }
            },
            "pic": {
                "read_only": True
            }

        }


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("name",)
        extra_kwargs = {
            "name": {
                "required": True,
                "min_length": 2,
                "error_messages": {
                    "required": "用户名必须提供",
                    "min_length": "用户名不得少于两个字符",
                }
            },
        }
